//
//  SWCheckoutViewController.swift
//  ChildStory
//
//  Created by linhan on 2017/1/14.
//  Copyright © 2017年 Aiya. All rights reserved.
//

import Foundation
import UIKit

enum FormAction:String
{
    case userName
    case phone
    case region //省市区
    case block  //镇街道
    case postcode
}

struct FormItem
{
    var title:String
    var action:FormAction
    var detail:Any?
    var icon:UIImage?
    var keyboardType:UIKeyboardType = .default
    var cell:UITableViewCell?
    
    init(title:String, action:FormAction)
    {
        self.title = title
        self.action = action
    }
}

class SWCheckoutViewController: SWBaseViewController,UITableViewDataSource,UITableViewDelegate,ClickActionDelegate,SWAPIComponent
{
    
    
    
    private var _selectedPackageIndex:Int = 0
    private var _packages:[SWProductPackage] = []
    
    private let SeparatorInset = UIEdgeInsetsMake(0, 15, 0, 15)
    private var _settings:[FormItem] = []
    
    private var _addresseeInfo:SWAddresseeInfo = SWAddresseeInfo()
    private var _addresseeInfoChanged:Bool = false
    
    private var _tableViewNormalHeight:CGFloat = 0
    private var _headerView:SWPackageHeaderView?
    
    lazy private var _toolBar:UIToolbar = UIToolbar()
    lazy private var _submitBtn:UIButton = UIButton(type:.system)
    lazy private var _tableView:UITableView = UITableView()
    
    deinit
    {
        trace("DEINIT SWCheckoutViewController")
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    private func setup()
    {
        let nameItem = FormItem(title: "收件人", action:.userName)
        _settings.append(nameItem)
        
        var phoneItem = FormItem(title: "联系电话", action:.phone)
        phoneItem.keyboardType = .phonePad
        _settings.append(phoneItem)
        
        let regionItem = FormItem(title: "地区", action:.region)
        _settings.append(regionItem)
        
        let blockItem = FormItem(title: "街道", action:.block)
        _settings.append(blockItem)
        
        
        //工具栏
        let completeBtn = UIBarButtonItem(title: "完成", style: .plain, target: self, action: #selector(completeBtnTapped))
        let spaceBtn = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
        
        _toolBar.sizeToFit()
        _toolBar.tintColor = UIColor.darkGray
        _toolBar.barTintColor = UIColor.white
        _toolBar.items = [spaceBtn, completeBtn]
        
        let submitBtnHeight:CGFloat = 40
        
        let package1:SWProductPackage = SWProductPackage()
        package1.title = "简装"
        package1.detailURL = "https://mp.weixin.qq.com/s/AONUrMT36jYBFNeg_VGIFA"
        let package2:SWProductPackage = SWProductPackage()
        package2.title = "精装"
        package2.detailURL = "https://mp.weixin.qq.com/s/mVVAG4jJTYu5B7aj8PaSWw"
        let package3:SWProductPackage = SWProductPackage()
        package3.title = "至尊"
        package3.detailURL = "https://mp.weixin.qq.com/s/6TAVYqrgtlJ6s6bi2y9FTA"
        let packages:[SWProductPackage] = [package1, package2, package3]
        _packages = packages
        
        //套装选择
        let headerView:SWPackageHeaderView = SWPackageHeaderView(frame: CGRectMake(0,0,view.width,150))
        headerView.delegate = self
        headerView.packages = packages
        headerView.selectedIndex = _selectedPackageIndex
        _headerView = headerView
        
        _tableViewNormalHeight = view.height - submitBtnHeight
        _tableView.frame = CGRectMake(0, 0, view.width, _tableViewNormalHeight)
        _tableView.dataSource = self
        _tableView.delegate = self
        _tableView.backgroundColor = UIColor.white
        _tableView.tableHeaderView = headerView
        _tableView.tableFooterView = UIView()
        _tableView.separatorColor = UIColor(hex: 0xe1e1e1)
        view.addSubview(_tableView)
        _tableView.separatorInset = SeparatorInset
        if #available(iOS 8.0, *) {
            _tableView.layoutMargins = SeparatorInset
        }
        
        
        _submitBtn.frame = CGRectMake(0, view.height - submitBtnHeight, view.width, submitBtnHeight)
        _submitBtn.backgroundColor = UIColor.lightGray
        _submitBtn.setTitle("提交", for: .normal)
        _submitBtn.addTarget(self, action: #selector(submitBtnTapped), for: .touchUpInside)
        _submitBtn.isEnabled = false
        view.addSubview(_submitBtn)
        
        let notification:NotificationCenter = NotificationCenter.default
        notification.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        notification.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
        
        
        fetchMajorAddresseeInfo()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return _settings.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let index:Int = indexPath.row
        var cell:UITableViewCell?
        if let item = _settings.valueAt(index)
        {
            if let aCell = item.cell
            {
                cell = aCell
            }
            else
            {
                if item.action == .region
                {
                    cell = SWRegionPickerFormCell(style: UITableViewCellStyle.value1, reuseIdentifier: "FormPickerCell")
                    let picker:SWRegionPicker = SWRegionPicker(frame: CGRectMake(0, 0, view.width, 160))
                    picker.cancelCallback = {[weak self] in self?.regionPickerCancelCallback()}
                    picker.chooseCallback = {[weak self] province,city,district in
                        self?.regionPickerChooseCallback(province, city: city, district: district)
                    }
                    (cell as? FormPickerCell)?.picker = picker
                    cell?.textLabel?.text = item.title
                }
                else
                {
                    cell = SWTextInputFormCell(item: item, cellWidth: view.width)
                    (cell as? SWTextInputFormCell)?.toolBar = _toolBar
                    (cell as? SWTextInputFormCell)?.textDidChangeCallback = {[weak self] in
                     self?.textInputTextDidChangeCallback()
                    }
                    
                }
                
                _settings[index].cell = cell
            }
            let detail:Any? = item.detail
            (cell as? SWFormCell)?.value = detail
        }
        return cell ?? UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        tableView.deselectRow(at: indexPath, animated: true)
        let index:Int = indexPath.row
        if let item = _settings.valueAt(index)
        {
            if item.action == .region
            {
                if let cell = cellForAction(item.action) as? FormPickerCell
                {
                    cell.focus()
                }
            }
        }
    }
    
    func view(_ view:UIView, click action:String, argument aArgument:[AnyHashable:Any]?)
    {
        if action == CallbackAction.Select
        {
            if let index = aArgument?[SWKey.index] as? Int
            {
                _headerView?.selectedIndex = index
                _selectedPackageIndex = index
            }
        }
        else if action == CallbackAction.Detail
        {
            let viewController = SWPackageChooseViewController(packages: _packages, selectedIndex: _selectedPackageIndex)
            viewController.chooseCallback = {[weak self] index in
                self?._headerView?.selectedIndex = index
                self?._selectedPackageIndex = index
            }
            navigationController?.pushViewController(viewController, animated: true)
        }
    }
    
    private func cellForAction(_ action:FormAction) -> UITableViewCell?
    {
        if let index = _settings.index(where: {$0.action == action}),
           let item = _settings.valueAt(index)
        {
            return item.cell
        }
        return nil
    }
    
    private func setValueForAction(_ action:FormAction, value:Any?)
    {
        if let index = _settings.index(where: {$0.action == action}),
           let value = value
        {
            _settings[index].detail = value
        }
    }
    
    //地址选择器关闭
    private func regionPickerCancelCallback()
    {
        view.endEditing(true)
    }
    
    //地址选择器关闭
    private func regionPickerChooseCallback(_ province:SWRegionItem, city:SWRegionItem, district:SWRegionItem)
    {
        let region:String = "\(province.title)\(city.title)\(district.title)"
        if let cell = cellForAction(FormAction.region)
        {
            cell.detailTextLabel?.text = region
        }
        setValueForAction(.region, value: region)
        
        
        _addresseeInfo.provinceCode = province.code
        _addresseeInfo.provinceName = province.title
        _addresseeInfo.cityCode = city.code
        _addresseeInfo.cityName = city.title
        _addresseeInfo.districtCode = district.code
        _addresseeInfo.districtName = district.title
        
        _addresseeInfoChanged = true
        formAvailabilityCheck()
        view.endEditing(true)
    }
    
    //地址内容修改
    private func textInputTextDidChangeCallback()
    {
        _addresseeInfoChanged = true
    }
    
    private func createAddresseeInfo(info:SWAddresseeInfo)
    {
        let req = SWAddressCreateReq(info: info)
        req.successCallback = {[weak self] response,_ in
            if let response = (response as? SWAddressCreateRsp)?.info,
                let info = SWAddresseeInfo(response: response),info.valid
            {
                self?._addresseeInfoChanged = false
                self?._addresseeInfo = info
                self?.submit(addresseeInfo: info, product: 0)
            }
            else
            {
                SVProgressHUD.showError(withStatus: "提交失败，请重试")
            }
        }
        req.failCallback = {[weak self] error in
            SVProgressHUD.showError(withStatus: error.message)
        }
        load(req)
    }
    
    //提交订单
    private func submit(addresseeInfo:SWAddresseeInfo, product:Any)
    {
        SWTransactionManager.sharedManager().submitOrder(addresseeInfo: addresseeInfo, product: 1, successCallback: {[weak self] requisition in
            self?.orderSubmitSuccessHandler(requisition: requisition)
            
            }, failCallback: {[weak self] error in
                SVProgressHUD.showError(withStatus: error.message)
        })
    }
    
    //订单成功提交后续处理
    private func orderSubmitSuccessHandler(requisition:SWPurchaseRequisition)
    {
        SVProgressHUD.dismiss()
        let paymentViewController = SWPaymentViewController(requisition: requisition)
        
        //let whiteList:[AnyClass] = [SWIndexViewController.self, SWProfileViewController.self]
        let tempControllers:[UIViewController] = navigationController?.viewControllers ?? []
        var viewControllers:[UIViewController] = []
        
        if let viewController = tempControllers.filter({$0 is SWIndexViewController}).valueAt(0)
        {
            viewControllers.append(viewController)
        }
        
        if let viewController = tempControllers.filter({$0 is SWProfileViewController}).valueAt(0)
        {
            viewControllers.append(viewController)
        }
        
        let orderViewController = SWOrderDetailViewController(orderID: requisition.orderID)
        viewControllers.append(orderViewController)
        viewControllers.append(paymentViewController)
        
        navigationController?.pushViewController(viewController: paymentViewController, completion: {[weak self] in
            self?.navigationController?.viewControllers = viewControllers
        })
        
    }
    
    //检查表单是否完整
    private func formAvailabilityCheck()
    {
        guard let name = (cellForAction(.userName) as? SWFormCell)?.value as? String ??? _addresseeInfo.receiver,name != "" else{
            return
        }
        
        guard let phone = (cellForAction(.phone) as? SWFormCell)?.value as? String ??? _addresseeInfo.phone,phone != "" else{
            return
        }
        
        guard let block = (cellForAction(.block) as? SWFormCell)?.value as? String ??? _addresseeInfo.block,block != "" else{
            return
        }
        
        _addresseeInfo.receiver = name
        _addresseeInfo.phone = phone
        _addresseeInfo.block = block
        
        _submitBtn.isEnabled = true
    }
    
    //获取地址信息
    private func fetchMajorAddresseeInfo()
    {
        let req = SWAddresseeInfoFetchReq()
        req.successCallback = {[weak self] response,_ in
            if let response = (response as? SWAddresseeInfoFetchRsp)?.info,
               let info = SWAddresseeInfo(response: response)
            {
                self?._addresseeInfo = info
                self?.updateAddresseeInfoView(info:info)
            }
        }
        load(req)
    }
    
    //更新地址视图信息
    private func updateAddresseeInfoView(info:SWAddresseeInfo)
    {
        var region:String = info.provinceName ?? ""
        region += info.cityName ?? ""
        region += info.districtName ?? ""
        setValueForAction(.userName, value:info.receiver)
        setValueForAction(.region, value:region)
        setValueForAction(.phone, value:info.phone)
        setValueForAction(.postcode, value:info.postcode)
        setValueForAction(.block, value:info.block)
        _tableView.reloadData()
        
        formAvailabilityCheck()
    }
    
    //键盘即将浮出
    @objc private func keyboardWillShow(_ notification:Notification)
    {
        if let userInfo = notification.userInfo
        {
            if let rect = userInfo[UIKeyboardFrameEndUserInfoKey] as? CGRect
            {
                let indexPath:IndexPath = IndexPath(row: _settings.count - 1, section: 0)
                UIView.animate(withDuration: 0.3, animations: {
                    self._tableView.height = self._tableViewNormalHeight - rect.height
                },completion:{finish in
                    self._tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
                })
            }
        }
    }
    
    //键盘即将隐藏
    @objc private func keyboardWillHide(_ notification:Notification)
    {
        UIView.animate(withDuration: 0.3, animations: {
            self._tableView.height = self._tableViewNormalHeight
        })
    }
    
    @objc private func completeBtnTapped()
    {
        view.endEditing(true)
        formAvailabilityCheck()
    }
    
    @objc private func submitBtnTapped()
    {
        if _addresseeInfoChanged || !_addresseeInfo.valid
        {
            guard let name = (cellForAction(.userName) as? SWFormCell)?.value as? String,name != "" else{
                SVProgressHUD.showError(withStatus: "输入收件人姓名")
                return
            }
            
            guard let phone = (cellForAction(.phone) as? SWFormCell)?.value as? String,phone != "" else{
                SVProgressHUD.showError(withStatus: "输入收件人电话")
                return
            }
            
            guard let block = (cellForAction(.block) as? SWFormCell)?.value as? String,block != "" else{
                SVProgressHUD.showError(withStatus: "输入收件人地址")
                return
            }
            
            if _addresseeInfo.provinceCode <= 0 || _addresseeInfo.cityCode <= 0 || _addresseeInfo.districtCode <= 0
            {
                SVProgressHUD.showError(withStatus: "输入收件人地址")
                return
            }
            
            
            _addresseeInfo.receiver = name
            _addresseeInfo.phone = phone
            _addresseeInfo.block = block
            
            SVProgressHUD.show(withStatus: "订单提交中...")
            createAddresseeInfo(info: _addresseeInfo)
        }
        else
        {
            SVProgressHUD.show(withStatus: "订单提交中...")
            submit(addresseeInfo: _addresseeInfo, product: 0)
        }
    }
    
    
    
}
